<?php

namespace App\Events\Chat;

use App\Events\Command;

class GroupsCommand extends Command
{
    // 说话
    public function chat($client_id, $data)
    {
        // 可以对好友说话
        // 也可以对自己说话
        try{
            // 如果用户id不存在
            $this->throwIf(empty($data['uid']), '请传递你的用户id！');
            $this->throwIf(empty($data['group_id']), '请传递你的群组id！');
            $this->throwIf(empty($data['say']), '请传递你要说的话！');
            
            // 保存聊天记录
            // 跨域请求
            $send   = ['uid' => $data['uid'], 'group_id' => $data['group_id'], 'message' => $data['say'], 'members' => 1,];
            $other  = ['model' => 'chat_groups_message'];
            $result = $this->curlChat('groups_message@add', $other, [], $send);
            $json   = json_decode($result, 1);
            $code   = isset($json['code']) ? $json['code'] : '';
            
            
            // 跨域返回消息
            $this->outputSend('跨域请求返回消息', $json['msg']);
            //$this->sendToCurrentClient($result);
            //$this->sendToCurrentClient($json);
            //$this->outputSend('跨域请求返回消息', $json['data']);
            // 如果成功 向所有人发送消息 TODO
            if ($code == 200) {
                $members = isset($json['data']['member']) ? $json['data']['member'] : [];
                $re_id   = isset($json['data']['id']) ? $json['data']['id'] : 0;
                $say     = ['uid' => $data['uid'], 'group_id' => $data['group_id'], 'message' => $data['say'], 'id' => $re_id,];
                $sayData = $this->success($say);
                foreach ($members as $it) {
                    $this->sendToUid($it, $sayData);
                }
            }
        } catch (Exception $e){
            $this->errorJsonToCurrentClient($e->getMessage(), $e->getCode());
        }
    }
    
    // 获取聊天记录
    
}